import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import http from '../plugins/http'
import store from '../store'


Vue.use(VueRouter)

  const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/brand/list',
    component: () => import('../views/brand/list.vue')
  },
  {
    path: '/cate/list',
    component: () => import('../views/cate/list.vue')
  },
  {
    path: '/user/list',
    component: () => import('../views/user/list.vue')
  },
  {
    path: '/role/list',
    component: () => import('../views/role/list.vue')
  },
  {
    path: '/product/list',
    component: () => import('../views/product/list.vue')
  },
  {
    path: '/cate/create',
    component: () => import('../views/cate/save.vue')
  },
  {
    path: '/cate/edit/:id',
    component: () => import('../views/cate/save.vue')
  },
  {
    path: '/brand/create',
    component: () => import('../views/brand/save.vue')
  },
  {
    path: '/brand/edit/:id',
    component: () => import('../views/brand/save.vue')
  },
  {
    path: '/product/create',
    component: () => import('../views/product/save.vue')
  },
  {
    path: '/product/edit/:id',
    component: () => import('../views/product/save.vue')
  },
  {
    path: '/user/create',
    component: () => import('../views/user/save.vue')
  },
  {
    path: '/user/edit/:id',
    component: () => import('../views/user/save.vue')
  },
  {
    path: '/user/permission/:id',
    component: () => import('../views/user/permission.vue')
  },
  {
    path: '/role/create',
    component: () => import('../views/role/save.vue')
  },
  {
    path: '/role/edit/:id',
    component: () => import('../views/role/save.vue')
  },
  {
    path: '/role/permission/:id',
    component: () => import('../views/role/permission.vue')
  },
  {
    path: '/data/sale',
    component: () => import('../views/data.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path == '/login'){
    next()
  }else {
    if(store.state.user.id){
      next()
    }else{
      http.get('/user/info').then(res => {
        if (res.errcode == 0){
          store.commit('setUser', res.data)
          next()
        }else{
          router.push('/login')
        }
      })  
    }
  }
})

export default router
